<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\StatusConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Mapper\ChCorpMapper;
use App\CustHub\Model\ChCorp;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChSendConfig;
use App\Setting\Service\SettingConfigService;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use function Yansongda\Supports\data_get;

class ChSendConfigService extends AbstractService
{
    public $mapper;
    public $defaultConfig = [];

    public function __construct(ChCorpMapper $mapper)
    {
        $this->mapper = $mapper;
        $this->defaultConfig = [];
    }


    public function getConfig($type,$uid,$robot_id = 0,$isMain = false)
    {
       $info =  ChSendConfig::query()
           ->where('type',$type)
           ->where(function ($query) use ($uid,$isMain){
               if($isMain){
                   $query->where('main_uid',$uid);
               }else{
                   $query->where('uid',$uid);
               }
           })
           ->when(filled($robot_id),function ($query) use ($robot_id){
               $query->where('robot_id',$robot_id);
           })
           ->first();
       if(!empty($info)){
           return  $info['value'];
       }

       return $this->getSystemDefaultCfgByType($type);
    }

    public function getConfigList(array $data)
    {
        $type = $data['type'];
        $group_id = data_get($data,'group_id',0);
        $keyword = data_get($data,'keyword');
        $corp_id = data_get($data,'corp_id');
        $where = [];
        //$where['c.uid'] = $data['uid'];
        if (not_empty($group_id)) {
            $where['ch_robot.group_id'] = $group_id;
        }
        if (not_empty($keyword)) {
            $where['ch_robot.nickname'] = ['like', "%" . $keyword . "%"];
        }
        if (not_empty($corp_id)) {
            $where['ch_robot.corp_id'] = $corp_id;
        }
        $list = ChRobot::query()
            ->withPermission((int)$data['uid'])
            -> leftJoin('ch_send_config as c',function($join)use($type,$data) {
                $join->on('c.robot_id', '=', 'ch_robot.id')
                    ->where('c.type', '=', $type) // 在 JOIN 条件中进行过滤
                    ->where('c.uid', '=', $data['uid']); // 在 JOIN 条件中进行过滤
            })
            -> select(['ch_robot.id as robot_id','ch_robot.nickname as robot_name','ch_robot.avatar as robot_avatar','ch_robot.corp_name as robot_corp_name','c.id as config_id','c.value','ch_robot.corp_id'])
            -> where($where)
            -> paginate();
        $defaultConfig = $this->getSystemDefaultCfgByType($type);
        $list->getCollection()->transform(function ($item) use($defaultConfig){
            $item -> value = !empty($item -> value)?json_decode($item -> value,true):$item -> value;
            if(empty($item -> config_id)){
                $item->value = $defaultConfig;
            }
            return $item;
        });
        return $this->mapper->setPaginate($list);
    }

    /**
     * 获取配置列表
     * @param mixed $type
     * @return array
     */
    public function getConfigMapByType(mixed $uid,mixed $type,$isMain = true): array
    {
        $data = ChSendConfig::query()
            ->where(function ($query) use ($uid,$isMain){
                if($isMain){
                    $query->where('main_uid',$uid);
                }else{
                    $query->where('uid',$uid);
                }
            })
            ->where('type',$type)
            ->where('status',StatusConstants::ENABLE)
            ->pluck('value','robot_id')
            ->toArray();
        return $data;
    }

    public function getSystemDefaultCfgByType(mixed $type)
    {
        $defaultType = SendConfigConstants::getDefaultType($type);
        if(!empty($defaultType)){
            $settingConfig = container()->get(SettingConfigService::class)->getConfigByKey($defaultType);
            return !empty($settingConfig['value'])?json_decode($settingConfig['value'],true):null;
        }else{
            return [];
        }
    }


    public function saveConfig($type,$uid,$main_uid,$corp_id,$robot_id,$value)
    {
        if(!is_array($value)) $value = json_decode($value,true);
        return ChSendConfig::query() -> updateOrCreate([
            'uid' => $uid,
            'robot_id' => $robot_id,
            'type' => $type,
        ],['corp_id' => $corp_id,'main_uid' => $main_uid,'value' => $value]);
    }

    /**
     * 判断是否在休息时间
     * @param mixed $uid
     * @param mixed $robotId
     * @param int $type 类型
     * @param bool $isMain 是否主账号
     * @return bool
     */
    public function isWithinSleepTime(mixed $uid, mixed $robotId, int $type, bool $isMain = false): bool
    {
        $config = $this->getConfig($type,$uid,$robotId,$isMain);
        if(empty($config)){
            return false;
        }

        $switch = data_get($config,'sleep_period_switch',0);
        if(!$switch){
            return false;
        }

        $sleepPeriodCfg = data_get($config,'sleep_period_cfg',[]);
        $needToSleep = false;
        foreach ($sleepPeriodCfg as $item){
            list($sleepStartTime,$sleepEndTime) = get_sleep_time($item['start_time'],$item['end_time']);
            if($sleepStartTime <= time() && time() <= $sleepEndTime){
                $needToSleep = true;
                break;
            }
        }
        return $needToSleep;
    }
}